package com.bjpowernode.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.bjpowernode.entity.TTranHistory;
import com.bjpowernode.entity.query.TranHistoryQuery;
import com.bjpowernode.mapper.TTranHistoryMapper;
import com.bjpowernode.mapper.TTranMapper;
import com.bjpowernode.service.TranHistoryService;
import com.bjpowernode.util.LoginInfoUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@RequiredArgsConstructor
@Slf4j
public class TranHistoryServiceImpl implements TranHistoryService {

    private final TTranHistoryMapper tranHistoryMapper;

    private final TTranMapper tranMapper;


    @Override
    @Transactional
    public int saveTranHistory(TranHistoryQuery tranHistoryQuery) {
        log.info("保存交易历史记录: {}", tranHistoryQuery);
        Integer currentUserId = LoginInfoUtil.getCurrentLoginUser().getId();
        TTranHistory tTranHistory = new TTranHistory();
        BeanUtil.copyProperties(tranHistoryQuery, tTranHistory);
        tTranHistory.setCreateBy(currentUserId);
        tTranHistory.setCreateTime(new Date());
        int flag = tranHistoryMapper.insert(tTranHistory);

        //更新交易阶段
        if (flag > 0) {

            if(tranMapper.updateStage(tTranHistory.getTranId(), tTranHistory.getStage(), new Date(), currentUserId) < 1){
                throw new RuntimeException("更新交易阶段失败");
            }
            return flag;
        }else {
            return -1;
        }
    }
}
